package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.FocusUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FocusUserApiImpl implements FocusUserApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<FocusUser> getByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = new Query();
        if (page != null && pagesize != null) {
            query.addCriteria(Criteria.where("userId").is(userId))
                    .with(PageRequest.of(page - 1, pagesize))
                    .with(Sort.by(Sort.Direction.DESC, "created"));
        }else {
            query.addCriteria(Criteria.where("userId").is(userId))
                    .with(Sort.by(Sort.Direction.DESC, "created"));
        }
        return mongoTemplate.find(query,FocusUser.class);
    }

    @Override
    public List<FocusUser> getFans(Long userId, Integer page, Integer pagesize) {
        Query query = new Query();
        if (page != null && pagesize != null) {
            query.addCriteria(Criteria.where("followUserId").is(userId))
                    .with(PageRequest.of(page-1, pagesize))
                    .with(Sort.by(Sort.Direction.DESC, "created"));
        }else {
            query.addCriteria(Criteria.where("followUserId").is(userId))
                    .with(Sort.by(Sort.Direction.DESC, "created"));
        }
        List<FocusUser> focusUsers = mongoTemplate.find(query, FocusUser.class);
        return focusUsers;
    }

    @Override
    public boolean exist(Long userId, Long focusId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("followUserId").is(focusId));
        return mongoTemplate.exists(query, FocusUser.class);
    }
}
